package cn.jorian.framework.net.converter;


import cn.jorian.framework.util.Base64Util;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import okhttp3.ResponseBody;
import retrofit2.Converter;

import java.io.IOException;
import java.io.StringReader;

public class GsonResponseBodyConverter2<T> implements Converter<ResponseBody, T> {

    private final Gson gson;
    private final TypeAdapter<T> adapter;

    GsonResponseBodyConverter2(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override public T convert(ResponseBody value) throws IOException {
        String decode = Base64Util.decode(value.string());
        StringReader stringReader = new StringReader(decode);
        JsonReader jsonReader = gson.newJsonReader(stringReader);
        try {
            return adapter.read(jsonReader);
        } finally {
            stringReader.close();
            value.close();
        }
    }
}
